package org.wattdepot.cli.command;

import java.io.BufferedWriter;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.util.List;
import javax.xml.datatype.XMLGregorianCalendar;
import org.wattdepot.cli.processor.CommandLineInterface;
import org.wattdepot.client.BadXmlException;
import org.wattdepot.client.MiscClientException;
import org.wattdepot.client.NotAuthorizedException;
import org.wattdepot.client.ResourceNotFoundException;
import org.wattdepot.util.tstamp.Tstamp;

/**
 * Constructor to handle Exceptions.
 * 
 * @author Remy Baumgarten
 * @author Kevin Chiogioji
 * 
 */
public class ChartPower extends CommandLineInterface implements WattDepotCliCommand {

  /**
   * Command 2.10 - Returns URL for a chart that displays power generated during a specified
   * interval.
   * 
   * @param args - List of parameters read in from the command line.
   * @return - Status of file creation.
   */
  public String doCommand(List<String> args) {
    String type;
    String source;
    String startDay;
    String endDay;
    int interval;
    String fileName;
    XMLGregorianCalendar startTime = null;
    XMLGregorianCalendar endTime = null;
    XMLGregorianCalendar currentInterval = null;
    StringBuffer buffer = new StringBuffer(2000);
    Double power = null;
    Double minPower = 1000000000000000.0;
    Double maxPower = 0.0;
    try {
      type = args.get(0);
      source = args.get(1);
      startDay = args.get(2);
      endDay = args.get(3);
      interval = Integer.parseInt(args.get(4));
      fileName = args.get(5);
      startTime = Tstamp.makeTimestamp(startDay);
      endTime = Tstamp.makeTimestamp(endDay);

    }
    catch (NumberFormatException nfe) {
      return "Your sampling-interval is not in range";
    }
    catch (Exception e) {
      return errorTimeStamp;
    }

    currentInterval = startTime;

    buffer.append("http://chart.apis.google.com/chart?chs=250x100&cht=lc&chd=t:");
    try {

      // Iterate through readings in specified intervals
      while (Tstamp.lessThan(currentInterval, endTime)) {
        if (type.equalsIgnoreCase("generated")) {
          power = client.getPowerGenerated(source, currentInterval) / 1000000;
        }
        else if (type.equalsIgnoreCase("consumed")) {
          power = client.getPowerConsumed(source, currentInterval) / 1000000;
        }
        buffer.append(String.format("%.1f,", power));
        if (power < minPower) {
          minPower = power;
        }
        if (power > maxPower) {
          maxPower = power;
        }
        // Increment current interval for next reading
        currentInterval = Tstamp.incrementMinutes(currentInterval, interval);
      }
    }
    catch (NotAuthorizedException nae) {
      return errorClient;
    }
    catch (ResourceNotFoundException rnfe) {
      return error404;
    }
    catch (BadXmlException bxe) {
      return errorXML;
    }
    catch (MiscClientException mce) {
      return errorClient;
    }
    buffer.deleteCharAt(buffer.length() - 1);
    buffer.append(String.format("&chds=%.1f,%.1f&chxt=y&chxr=0,%.1f,%.1f", minPower, maxPower,
        minPower, maxPower));
    try {
      FileWriter fwo = new FileWriter(fileName, false);
      BufferedWriter bwo = new BufferedWriter(fwo);
      bwo.write("<html>");
      bwo.write("<head>");
      bwo.write("<title>" + source + '-' + startDay + " " + endDay + " Chart </title>");
      bwo.write("</head>");
      bwo.write("<body>");
      bwo.write("<img src=" + buffer.toString() + "/>");
      bwo.write("</body");
      bwo.write("</html>");
      bwo.close();
    }
    catch (FileNotFoundException fne) {
      return errorFile;
    }
    catch (IOException ioe) {
      return errorFile;
    }
    buffer.append("HTML File Generated: ").append(fileName);
    return "HTML Generated";
  }
}
